<?php
/**
 * 抓取数据赛事匹配队列
 * User: Owen Zhang
 * Date: 2020/3/17
 * Time: 中午10:24
 */

namespace app\queue;

use think\facade\Log;
use think\queue\Job;

class EventWormMatchQueue
{

    // sudo nohup php think queue:work --daemon --queue eventWormMatchQueue --tries 2 >  out.file  2>&1  &
    //sudo php think queue:work --daemon --queue eventWormMatchQueue
    //消费队列
    //$data=['id'=>123,'type'=>'xl']
    //id = xl_event_id
    public function perform($data)
    {
        Log::record('perform开始消费赛事爬取队列data:' . json_encode($data));
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('Owen.123tx'); //密码验证
        $key = 'test';
        $redis->incr($key);
        if (!$redis->expire($key, 600)) {
            Log::record('perform消费赛事爬取队列失败data:' . json_encode($data));
            return false;
        }
        return true;
    }

    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        Log::record('fire开始消费赛事爬取队列data:' . json_encode($data));
        //消费队列
        $isJobDone = $this->perform($data);

        if ($isJobDone) {
            Log::record('fire成功消费赛事爬取队列data:' . json_encode($data));
            //如果任务执行成功， 记得删除任务
            $job->delete();
        } else {
            //检查任务重试3次数后删除队列
            if ($job->attempts() > 3) {
                $job->delete();
            }
        }
    }
}
